package com.yj.service.impl;

import com.yj.entity.Collectionss;
import com.yj.entity.Details;
import com.yj.entity.Houses;
import com.yj.entity.Region;
import com.yj.entity.Users;
import com.yj.dao.CollectionssMapper;
import com.yj.dao.DetailsMapper;
import com.yj.dao.HousesMapper;
import com.yj.dao.RegionMapper;
import com.yj.dao.UsersMapper;
import com.yj.service.IHousesService;
import com.yj.util.Gd;
import com.yj.util.PageUtil;
import com.yj.util.UpLoad;
import com.yj.vo.JsonResult;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageInfo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author yj
 * @since 2020-08-24
 */
@Service
public class HousesServiceImpl extends ServiceImpl<HousesMapper, Houses> implements IHousesService {

	private final int pageSize = 6;

	@Autowired
	HousesMapper houses;

	@Autowired
	RegionMapper region;

	@Autowired
	UsersMapper users;

	@Autowired
	DetailsMapper detailsMapper;
	
	@Autowired
	CollectionssMapper coll;

	@Override
	public JsonResult pages() {
		JsonResult ret = null;
		QueryWrapper<Houses> wrapper = new QueryWrapper<Houses>();
		wrapper.eq("state", "未售");
		PageInfo<Houses> pageInfo = PageUtil.test(0, pageSize, houses, wrapper);
		int[] nums = pageInfo.getNavigatepageNums();
		if (nums != null && nums.length != 0) {
			ret = new JsonResult(true, "页码查询成功");
			ret.setData("pages", nums);
			return ret;
		} else {
			ret = new JsonResult(false, "页码查询失败");
			return ret;
		}
	}

	@Override
	public JsonResult page(int pageNum) {
		JsonResult ret = null;
		QueryWrapper<Houses> wrapper = new QueryWrapper<Houses>();
		wrapper.eq("state", "未售");
		PageInfo pageInfo = PageUtil.test(pageNum, pageSize, houses, wrapper);
		List<Houses> list = pageInfo.getList();
		if (list != null && pageInfo.getNavigatepageNums().length != 0) {
			ret = new JsonResult(true, "当前页数据查询成功");
			ret.setData("page", list);
			return ret;
		} else {
			ret = new JsonResult(false, "当前页查询失败");
			return ret;
		}
	}

	@Override
	public JsonResult find(String info) {

		JsonResult ret = new JsonResult(false, null);
		QueryWrapper<Region> wrapper = new QueryWrapper<>();
		wrapper.like("province", info).or().like("city", info).or().like("area", info).or().like("street", info);
		List<Region> list = region.selectList(wrapper);
		System.out.println(list + "list");
		List<Integer> didList = new ArrayList<Integer>();
		// 得到查询所有地区的uid
		if (list.size() != 0) {
			for (int i = 0; i < list.size(); i++) {
				didList.add(list.get(i).getDid());
			}
			QueryWrapper<Houses> wrapperhouse = new QueryWrapper<>();
			wrapperhouse.in("did", didList);
			PageInfo pageInfo = PageUtil.test(0, pageSize, houses, wrapperhouse);
			List<Houses> listHouses = pageInfo.getList();
			System.out.println(listHouses + "listHouses");
			if (pageInfo.getNavigatepageNums().length != 0) {
				ret.setSuccess(true);
				ret.setData("houselist", listHouses);
				System.out.println("ret" + ret);
				return ret;
			} else {

				ret.setSuccess(false);
				ret.setMessage("获取房源信息失败");
				return ret;
			}
		} else {
			ret.setMessage("获取房源信息失败");
			return ret;
		}
	}

	@Override
	public JsonResult findByType(JSONObject json) {
		JsonResult ret = null;
		List<Object> houseList = new ArrayList<Object>();

		QueryWrapper<Houses> wrapper = new QueryWrapper<Houses>();
		PageInfo pageInfo = null;
//		"province":null,"city":null,"low":null,"high":null,"min":null,"max":null
		int pageNum = (int) json.get("page");
		Object pro = json.get("province");
		Object city = json.get("city");
		Object low = json.get("low");
		Object high = json.get("high");
		Object min = json.get("min");
		Object max = json.get("max");

		if (low == null)
			low = 0;
		if (high == null)
			high = 2147483647;
		if (min == null)
			min = 0;
		if (max == null)
			max = 2147483647;

		wrapper.between("hsize", low, high);
		wrapper.between("price", min, max);
		wrapper.eq("state", "未售");

		if (pro != null) {
			if (city != null) {
				wrapper.apply("houses.did in (select b.did from region b where province='" + pro + "' and city='" + city
						+ "')");
			} else {
				wrapper.apply("houses.did in (select b.did from region b where province='" + pro + "')");
			}
		}

		pageInfo = PageUtil.test(pageNum, 6, houses, wrapper);

		if (pageInfo.getNavigatepageNums().length != 0) {
			Map<String, Object> m = new HashMap<String, Object>();
			m.put("sz", pageInfo.getNavigatepageNums());
			houseList.add(m);// 存分页数组
			List<Houses> list = pageInfo.getList();
			for (Houses hous : list) {
				String uname = users.selectById(hous.getUid()).getUname();
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("housename", uname);
				map.put("house", hous);
				houseList.add(map);// 存房东名字和房源信息
			}
			ret = new JsonResult(true, "全分类查询成功");
			ret.setData("houses", houseList);
			return ret;
		} else {
			ret = new JsonResult(false, "全分类查询未查到数据");
			return ret;
		}
	}

	@Override
	public JsonResult findHousesSize() {
		JsonResult ret = null;
		List<Double> allHouseSize = houses.AllHouseSize();
		if (allHouseSize != null && allHouseSize.size() != 0) {
			ret = new JsonResult(true, "所有未售房源大小查询成功");
			ret.setData("sizes", allHouseSize);
			return ret;
		} else {
			ret = new JsonResult(false, "查询所有房源大小失败");
			return ret;
		}
	}

	@Override
	public JsonResult findPrices() {
		JsonResult ret = null;
		List<Integer> allHousePrice = houses.AllHousePrice();
		if (allHousePrice != null && allHousePrice.size() != 0) {
			ret = new JsonResult(true, "所有未售房源价格查询成功");
			ret.setData("prices", allHousePrice);
			return ret;
		} else {
			ret = new JsonResult(false, "查询所有房源价格失败");
			return ret;
		}
	}

	// 推荐的受欢迎的七个房子
	@Override
	public JsonResult fondHouse() {
		JsonResult ret = null;
		List<Integer> list = houses.likehouseid();
		QueryWrapper<Houses> wrapper = new QueryWrapper<>();
		wrapper.eq("state", "未售");
		wrapper.in("hid", list);
		List<Houses> listhHouses = houses.selectList(wrapper);
		System.out.println(listhHouses);
		List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();

		for (Houses h : listhHouses) {
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("hid", h.getHid());
			map.put("uname", users.selectById(h.getUid()).getUname());
			map.put("house", h);
			resultList.add(map);
			System.out.println(resultList + "uu");
		}
		if (listhHouses.size() > 0) {
			ret = new JsonResult(true, "查询受欢迎的房子成功");
			ret.setData("fondhouse", resultList);

			return ret;
		} else {
			ret = new JsonResult(false, "查询受欢迎的房子失败");
			return ret;
		}

	}

	@Override
	public JsonResult showhousedetail(int hid) {
		JsonResult result = new JsonResult(false, null);
		Houses house = houses.selectById(hid);
		if (house != null) {
			Users user = users.selectById(house.getUid());
			String street = region.selectById(house.getDid()).getStreet();
			double[] arr = Gd.addressToGPS(street);
			//System.out.println("*******"+user+"--"+street+"--"+arr);
			if (user != null && street != null && arr != null) {
				result.setMessage("查询房子信息成功");
				result.setSuccess(true);

				result.setData("user", user);
				result.setData("house", house);
				result.setData("jingdu", arr[0]);
				result.setData("weidu", arr[1]);

			} else {
				result.setMessage("查询房子详细信息不全");
				result.setSuccess(false);
			}

		} else {
			result.setMessage("查询房子详细信息失败");
			result.setSuccess(false);
		}
		return result;
	}

	@Override

	public JsonResult updhouse(Houses house, Region regions) {
		JsonResult retJsonResult = new JsonResult(false, null);
		if (regions.getProvince() != null && regions.getCity() != null && regions.getArea() != null
				&& regions.getStreet() != null) {
			QueryWrapper<Region> wrapper = new QueryWrapper<>();
			HashMap map = new HashMap<>();
			map.put("province", regions.getProvince());
			map.put("city", regions.getCity());
			map.put("area", regions.getArea());
			map.put("street", regions.getStreet());
			wrapper.allEq(map);
			Region regi = region.selectOne(wrapper);
			house.setDid(regi.getDid());
			int num = houses.updateById(house);
			if (num > 0) {
				Houses houe = houses.selectById(house.getHid());
				retJsonResult.setMessage("更新成功");
				retJsonResult.setData("house", houe);
				retJsonResult.setSuccess(true);
			} else {
				retJsonResult.setMessage("房源信息更新失败");
			}
		} else {
			retJsonResult.setMessage("地址信息不全");

		}
		return retJsonResult;
	}

	@Override
	public JsonResult delhouse(int id) {
		JsonResult retJsonResult = new JsonResult(false, null);
		int num = houses.deleteById(id);
		int rnum = coll.delete(new QueryWrapper<Collectionss>().eq("hid", id));
		int did = detailsMapper.delete(new QueryWrapper<Details>().eq("hid", id));
//		System.out.println(num+"-"+rnum+"-"+did);
		if (num > 0&&rnum>0&&did>0) {
			retJsonResult.setMessage("删除成功");
			retJsonResult.setSuccess(true);
		}
		return retJsonResult;
	}

	@Override
	public JsonResult upHouseImg(int hid, HttpServletRequest request) {
		JsonResult ret = null;
		List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
		String imgNamejson = UpLoad.multiUpload(files);
		int n = houses.UpdateImgByHid(hid, imgNamejson);
		System.out.println(imgNamejson);
		if (n != 0) {
			ret = new JsonResult(true, "房源照片上传成功");
			ret.setData("imginfo", "ok");
			return ret;
		} else {
			ret = new JsonResult(false, "房源照片上传失败");
			return ret;
		}
	}

	@Override
	
	public JsonResult inserthouse(Houses house,Region regions,HttpSession session) {
		JsonResult retJsonResult=new JsonResult(false, null);
		QueryWrapper<Region> wrapper=new QueryWrapper<Region>();
		
		Object valueObject=session.getAttribute("usersession");
		if (valueObject!=null) {
			Users user=(Users)valueObject;
			if(regions.getProvince()!=null&&regions.getCity()!=null&&regions.getArea()!=null&&regions.getStreet()!=null) {
				house.setUid(user.getUid());
				HashMap<String,Object> map=new HashMap<String,Object>();
				map.put("province", regions.getProvince());
				map.put("city", regions.getCity());
				map.put("area", regions.getArea());
				map.put("street", regions.getStreet());
				wrapper.allEq(map);
				Region regi = region.selectOne(wrapper);
				house.setDid(regi.getDid());
				house.setState("未售");
				int num=houses.insert(house);
				if(num>0) {
					Houses houe=houses.selectById(house.getHid());
					retJsonResult.setMessage("房源信息插入成功");
					retJsonResult.setData("house", houe);
					retJsonResult.setSuccess(true);
				}else {
					retJsonResult.setMessage("房源信息插入更新失败");
				}
			}else {
				retJsonResult.setMessage("房源地址不完整");
			}
		}
		return retJsonResult;
	}

	@Override
	public JsonResult findbyUid(HttpSession session) {
		JsonResult retJsonResult = new JsonResult(false, null);
		Object valueObject = session.getAttribute("usersession");

		if (valueObject != null) {
			Users user = (Users) valueObject;
			QueryWrapper<Houses> wrapper = new QueryWrapper<>();
			wrapper.eq("uid", user.getUid());
			List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
			List<Houses> Houslist = houses.selectList(wrapper);

			if (Houslist.size() > 0) {
				for (Houses h : Houslist) {
					HashMap<String, Object> map = new HashMap<String, Object>();
					map.put("house", h);
					map.put("region", region.selectById(h.getDid()));
					list.add(map);
				}

				retJsonResult.setSuccess(true);
				retJsonResult.setData("listHouse", list);

			} else {
				retJsonResult.setMessage("没有查询到房子信息");
			}

		} else {
			retJsonResult.setMessage("请先登录");
		}
		return retJsonResult;
	}

	@Override
	public JsonResult findzufang(HttpSession session) {
		JsonResult retJsonResult = new JsonResult(false, null);
		Object valueObject = session.getAttribute("usersession");

		if (valueObject != null) {
			Users user = (Users) valueObject;
			QueryWrapper<Details> wrapper = new QueryWrapper<>();
			wrapper.eq("puid", user.getUid());
			List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
			List<Details> detaillist = detailsMapper.selectList(wrapper);// 查询详情表信息
			if (detaillist.size() > 0) {
				for (Details detail : detaillist) {
					HashMap<String, Object> map = new HashMap<String, Object>();
					map.put("detail", detail);
					map.put("fangdong", users.selectById(houses.selectById(detail.getHid()).getUid()).getUname());
					map.put("house", houses.selectById(detail.getHid()));
					map.put("region", region.selectById(houses.selectById(detail.getHid()).getDid()));
					list.add(map);
				}

				retJsonResult.setSuccess(true);
				retJsonResult.setData("listHouse", list);

			} else {
				retJsonResult.setMessage("没有查询到房子信息");
			}

		} else {
			retJsonResult.setMessage("请先登录");
		}
		return retJsonResult;
	}

	@Override
	public JsonResult findByDid(int did) {
		JsonResult ret = null;
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		QueryWrapper<Houses> wrapper = new QueryWrapper<Houses>();
		wrapper.eq("did", did);
		wrapper.eq("state", "未售");
		List<Houses> selectList = houses.selectList(wrapper);
		for (Houses ho : selectList) {
			String uname = users.selectById(ho.getUid()).getUname();
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("uname", uname);
			map.put("house", ho);
			list.add(map);
		}
		if (list != null && list.size() != 0) {
			ret = new JsonResult(true, "根据地区查询房源成功");
			ret.setData("info", list);
			return ret;
		} else {
			ret = new JsonResult(false, "根据地区查询房源失败");
			return ret;
		}
	}

}
